package com.shanshui.test.gm;

import java.io.InputStream;
import java.util.Collections;

import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.CipherSuite;
import okhttp3.ConnectionSpec;
import okhttp3.OkHttpClient;
import okhttp3.TlsVersion;

/**
 * @author mashanshui
 * @since 2025/11/14
 */
public class GmOkHttpClient {

    public static OkHttpClient.Builder getOkHttpClientBuilder(InputStream certChain) {
        GMSSLContext sslContext = new GMSSLContext(certChain);
        TrustManager[] trustManagers = sslContext.getTrustManagers();
        return getOkHttpClientBuilder(sslContext.getSslSocketFactory(), trustManagers);
    }

    public static OkHttpClient.Builder getOkHttpClientBuilder(String certChain) {
        GMSSLContext sslContext = new GMSSLContext(certChain);
        TrustManager[] trustManagers = sslContext.getTrustManagers();
        return getOkHttpClientBuilder(sslContext.getSslSocketFactory(), trustManagers);
    }

    public static OkHttpClient.Builder getOkHttpClientBuilder(TrustManager[] trustManagers) {
        GMSSLContext sslContext = new GMSSLContext(trustManagers);
        return getOkHttpClientBuilder(sslContext.getSslSocketFactory(), trustManagers);
    }

    private static OkHttpClient.Builder getOkHttpClientBuilder(SSLSocketFactory sslSocketFactory, TrustManager[] trustManagers) {
        ConnectionSpec spec = (new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS))
                .tlsVersions(TlsVersion.TLCPv1_1)
                .cipherSuites(CipherSuite.TLCP_ECC_SM4_GCM_SM3, CipherSuite.TLCP_ECC_SM4_CBC_SM3)
                .build();
        return new OkHttpClient.Builder()
                .sslSocketFactory(sslSocketFactory,
                        (X509TrustManager) trustManagers[0])
                .connectionSpecs(Collections.singletonList(spec))
                // Not check hostname
                .hostnameVerifier((hostname, session) -> true);
    }
}
